package com.live.video.server;

import com.live.video.mapper.GiftPlanMapper;
import com.live.video.model.GiftPlan;
import com.live.video.util.MySSDBPool;
import com.live.video.util.MyUtils;
import lombok.extern.slf4j.Slf4j;
import org.nutz.ssdb4j.spi.SSDB;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Description:
 * User: godd
 * Date: 2017-11-05
 * Time: 18:03
 */
@Slf4j
@Service
public class GiftServer implements BaseServer<GiftPlan> {

    @Autowired
    private GiftPlanMapper mapper;

    @Autowired
    @Lazy
    private MySSDBPool ssdbPool;

    private final String SET_GIFTS = "SET:GIFTS";
    private final String GIFT_MAP = "MAP:GIFT:";

    /**
     * 存储打赏礼物信息
     *
     * @author 戴长春    dcc@vtc365.com
     * @date 2017/11/5 18:10
     */
    @Override
    public void save(GiftPlan giftplan) {


        if (giftplan.getId() == null) {
            SSDB ssdb = ssdbPool.borrowSSDB();

            int insertRes = mapper.insert(giftplan);
            log.info("result:{},giftPlan:{}", insertRes, giftplan);

            if (ssdb != null) {
                String giftKey = GIFT_MAP + giftplan.getId();
                try {
                    Map<String, String> map = MyUtils.transBeanToMapExceptNull(giftplan);
                    String hmset = ssdb.multi_hset(giftKey, map).asString();
                    System.out.println(hmset);
                } catch (Exception e) {
                    e.printStackTrace();
                }

                ssdb.zset(SET_GIFTS, giftKey, giftplan.getGiftPrice());
            }
        } else {
            mapper.updateByPrimaryKeySelective(giftplan);
        }
    }

    /**
     * 获取所有的打赏方案
     *
     * @author 戴长春    dcc@vtc365.com
     * @date 2017/11/5 18:14
     */
    public List queryAll() {
        List giftplans = new ArrayList<>();
        SSDB ssdb = ssdbPool.borrowSSDB();
        List<String> gifts = ssdb.zrange(SET_GIFTS, 0, -1).listString();
        if (gifts == null || gifts.isEmpty()) {
            giftplans = mapper.selectAll();
        } else {
            System.out.println("缓存中有值，缓存中取");
            for (String giftKey : gifts) {
                Map<String, String> giftInfo = ssdb.hgetall(giftKey).mapString();
                giftplans.add(giftInfo);
            }
        }
        return giftplans;
    }

    @Override
    public GiftPlan queryOne(GiftPlan giftplan) {
        return null;
    }

    @Override
    public int remove(GiftPlan giftplan) {
        return 0;
    }
}
